﻿Number.prototype.formatMoney = function (decPlaces, thouSeparator, decSeparator) {
	var n = this,
	decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces,
	decSeparator = decSeparator == undefined ? "." : decSeparator,
	thouSeparator = thouSeparator == undefined ? "," : thouSeparator,
	sign = n < 0 ? "-$" : "$",
	i = parseInt(n = Math.abs(+n || 0).toFixed(decPlaces)) + "",
	j = (j = i.length) > 3 ? j % 3 : 0;
	return sign + (j ? i.substr(0, j) + thouSeparator : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thouSeparator) + (decPlaces ? decSeparator + Math.abs(n - i).toFixed(decPlaces).slice(2) : "");
};
function el(str) { return document.querySelector(str); }
function els(str) { return document.querySelectorAll(str); }
function ajax(url, params, func, func2) {
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.onreadystatechange = function () {//Call a function when the state changes.
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
			func(xmlhttp.responseText);
		}
		if (func2 != undefined && xmlhttp.readyState == 4) {
			func2();
		}
	}
	xmlhttp.open("POST", url, true);
	//xmlhttp.setRequestHeader("Content-type", "multipart/form-data");
	xmlhttp.send(params);
}
function ajaxTrSubmit(evt,str) {
	var elTr = evt.srcElement.parentElement.parentElement;
	if (str == undefined) str = "";
	var url = urlHost + elTr.parentElement.parentElement.getAttribute("data-controller") +"/"+str+ "_Edit";
	var elsi = els("tr#" + elTr.id + " input" + ':not([type="hidden"])');
	var isAdd = elTr.getAttribute("data-id") == "0";
	var data = new FormData();
	for (var i = 0; i < elsi.length; i++) {
		var name = elsi[i].getAttribute("name");
		if (elsi[i].getAttribute("type") == "checkbox") {
			data.append(name, elsi[i].checked);
			if (isAdd) elsi[i].checked =null;
		} else if (elsi[i].getAttribute("type") == "file") {
			data.append(name, elsi[i].files[0]);
			if (isAdd) elsi[i].files=null;
		} else {
			data.append(name, elsi[i].value);
			if (isAdd && !elsi[i].hasAttribute("readonly") && elsi[i].getAttribute("type") != "button")
				elsi[i].value = "";
		}
		elsi[i].classList.remove("input-validation-error");
	}
	elsi = els('tr#' + elTr.id + ' textarea,tr#' + elTr.id + ' select');
	for (var i = 0; i < elsi.length; i++) {
		var name = elsi[i].getAttribute("name");
		//data.append(name, htmlEncode(elsi[i].value));
		data.append(name, elsi[i].value);
	}
	ajax(url, data, function (ret) {
		ret = removeAdsStr(ret);
		z.status.saved();
		if (isRealTime) return;
		if (elTr.getAttribute("data-id") != "0")
			elTr.outerHTML = ret;
		else {
			var elTb = elTr.parentElement.parentElement;
			var eli = document.createElement("table");
			eli.innerHTML = ret;
			eli = eli.children[0].children[0];
			if (eli.getAttribute("data-id") == "0") {
				elTr.outerHTML = ret;
			}else if (elTb.children[1].children[0] != null)
				elTb.children[1].insertBefore(eli, elTb.children[1].children[0]);
			else
				elTb.children[1].appendChild(eli);
		}
		//CKEDITOR.replace(el("tr#id" + id + " .ckeditor"));
	});
}
function ajaxTrRefresh(str) {
	var strs = str.split(",");
	var elTb = el("table[data-controller=\"" + strs[0] + "\"]");
	if (elTb == null) return;
	var elTr = el("table[data-controller=\"" + strs[0] + "\"] tr[data-id=\"" + strs[1] + "\"]");
	var url = urlHost + elTb.getAttribute("data-controller") + "/_Show?ID=" + strs[1];
	ajax(url, null, function (ret) {
		z.status.loaded();
		if (elTr == null) {
			var eli = document.createElement("tr");
			elTb = elTb.children[1];
			elTb.appendChild(eli);
			if (elTb.children[0] != null)
				elTb.insertBefore(eli, elTb.children[0]);
			else
				elTb.appendChild(eli);
			eli.outerHTML = ret;
		} else {
			elTr.outerHTML = ret;
		}
	});
}
function ajaxTrBtn(evt, str) {
	var elTr = evt.srcElement.parentElement.parentElement;
	var elTb = elTr.parentElement;
	var data = new FormData();
	var url = urlHost + elTb.parentElement.getAttribute("data-controller") + "/_" + str;
	if (elTr.getAttribute("data-id") != null) {
		data.append("ID", elTr.getAttribute("data-id"));
	}
	if (elTb.parentElement.getAttribute("data-id") != null) {
		data.append("ParentID", elTb.parentElement.getAttribute("data-id"));
	}
	ajax(url, data, function (ret) {
		z.status.saved();
		if (isRealTime) return;
		if (str == "Add") {
			var eli = document.createElement("tr");
			elTb = elTb.parentElement.children[1];
			elTb.appendChild(eli);
			if (elTb.children[0] != null)
				elTb.insertBefore(eli, elTb.children[0]);
			else
				elTb.appendChild(eli);
			eli.outerHTML = ret;
		} else {
			elTr.outerHTML = ret;
		}
		//CKEDITOR.replace(el("tr#id" + id + " .ckeditor"));
	});
}
function htmlDecode(str) {
	return str
		.replace('&amp;',"&" )
		.replace( '&quot;',"\"")
		.replace('&#39;', "'")
		.replace('&lt;',"<" )
		.replace('&gt;',">" );
}
function htmlEncode(str) {
	return str
		.replace(/&/g, '&amp;')
		.replace(/"/g, '&quot;')
		.replace(/'/g, '&#39;')
		.replace(/</g, '&lt;')
		.replace(/>/g, '&gt;');
}
function openPopup(str, url) {
	el(str).innerHTML = "";
	ajax(url, "", function (ret) {
		el(str).innerHTML = ret;
		el(str).className = "";
	});
}
function showPopup(str) {
	el(str).className = "popup";
}
function closePopup(element) {
	element.className = "hidden";
	element.className = "popupHidden";
	setTimeout(
			function () {
				element.className = "hidden";
			}, 500);
}
function openPID() {
	el("#popup2").innerHTML = "";
	ajax(urlHost + "Product/List", "", function (ret) {
		el("#popup2").innerHTML = ret;
		el("#popup2").className = "";
	});
}
function closePID(id) {
	elPID.value = id;
	var elAdd = el('#oc_dt0 input[value="Add"]');
	if (elAdd == null) {
		elAdd = el('#or_dt0 input[value="Add"]');
	}
	if (id > 0) {
		elAdd.removeAttribute("disabled");
	} else {
		elAdd.setAttribute("disabled");
	}
	closePopup(el("#popup2"));
}
var mes;
function closeMessengerID(evt) {
	el('textarea[name="Messenger"]').value= htmlDecode( evt.srcElement.parentElement.parentElement
		.children[2].children[0].children[0].innerHTML);
	closePopup(evt.srcElement.parentElement.parentElement.parentElement.parentElement.parentElement);
}
z = {};
z.status = {
	saved: function () {
		el("#status").innerHTML = "Saved";
		el("#status").className = "status";
		setTimeout(
			function () {
				el("#status").className = "";
			}, 1000);
	},
	loaded: function () {
		el("#status").innerHTML = "Loaded new data";
		el("#status").className = "status";
		setTimeout(
			function () {
				el("#status").className = "";
			}, 1000);
	},
	offline: function () {
		el("#status").innerHTML = "You are off-line";
		el("#status").className = "highlight";
		//setTimeout(
		//	function () {
		//		el("#status").className = "";
		//	}, 1000);
	}
}
function zOnEnter(evt, func) {
	var key;

	if (window.event)
		key = window.event.keyCode; //IE
	else
		key = e.which; //Firefox & others

	if (key == 13) {
		func();
		return false;
	} else {
		return true;
	}
}
if (isRealTime) {
	socket = new WebSocket("ws://"+hostName+urlHost+"WebSocket");
	socket.addEventListener("close", function (evt) {
		z.status.offline();
		isRealTime = false;
	});
	socket.addEventListener("message", function (evt) {
		ajaxTrRefresh(evt.data);
		z.status.loaded();
	});
}
function removeAdsStr(str) {
	stri = "<!--SCRIPT GENERATED BY SERVER! PLEASE REMOVE-->";
	if (str.indexOf(stri) > 0)
		return str.substring(0, str.indexOf(stri));
	else
		return str;
}
function removeAds() {
	elBd = document.querySelector("body");
	eli = el("div#end");
	while (!elBd.lastChild.isEqualNode(eli)) {
		elBd.removeChild(elBd.lastChild);
	}
}
var editor;
function installEditor(str) {
	if (editor)
		editor.destroy();
	editor = CKEDITOR.replace(el(str + " textarea"));
}
function destroyEditor() {
	editor.destroy();
}